package com.markchu.modules.system.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.markchu.common.enums.StatusEnum;
import com.markchu.common.utils.HttpServletUtil;
import com.markchu.common.utils.StatusUtil;
import lombok.Data;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.annotations.Where;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;

/**
 * @author mark_chu
 * @date 2023/11/23
 */
@Data
@Entity
@Table(name="web_news")
@EntityListeners(AuditingEntityListener.class)
@Where(clause = StatusUtil.NOT_DELETE)
public class News implements Serializable {
    // 主键ID
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    // 标题
    private String title;

    private Long file_id;
    // 图片地址
    private String photo;
    // 文本内容
    @Lob
    private String contents;
    // 备注
    private String remark;
    // 来源
    private String original;
    // views
    private Integer views;
    // 创建时间
    @CreatedDate
    private Date createDate;
    // 更新时间
    @LastModifiedDate
    private Date updateDate;
    // 创建者
    @CreatedBy
    @ManyToOne(fetch=FetchType.LAZY)
    @NotFound(action=NotFoundAction.IGNORE)
    @JoinColumn(name="create_by")
    @JsonIgnore
    private User createBy;
    // 更新者
    @LastModifiedBy
    @ManyToOne(fetch=FetchType.LAZY)
    @NotFound(action=NotFoundAction.IGNORE)
    @JoinColumn(name="update_by")
    @JsonIgnore
    private User updateBy;
    // 数据状态
    private Byte status = StatusEnum.OK.getCode();

    public String getUrl() {
        if (!StringUtils.isEmpty(photo)) {
            return "/upload_pic" + photo;
        }
        return photo;
    }

    public String getSmallTitle() {
        if (!StringUtils.isEmpty(title) && contents.length()>13) {
            return title.substring(0,12)+"...";
        }
        return title;
    }

    public static String removeHtmlTags(String innerHtml){
        String regex = "<[^>]+>";
        return innerHtml.replaceAll(regex,"");
    }

    public String getSmallContents() {
        if (!StringUtils.isEmpty(contents)) {
            String outHtml = removeHtmlTags(contents);
            if(outHtml.length()>60){
                return outHtml.substring(0,58)+"...";
            }else{
                return outHtml;
            }
        }
        return contents;
    }

}